package com.interview.a_多线程.c_停止线程.e_无法停止_解决;

/**
 * try cath 在while里面 循环中添加判断条件依旧无法停止
 * <p>
 * sleep 设计如此 ，响应中断后 会重置中断的状态
 * <p>
 * 可以通过 恢复中断解决 
 * 这样后续的执行才能检查到发生了中断
 */
public class NotStopThread implements Runnable {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new NotStopThread());
        thread.start();

        //执行0.5秒时中断
        Thread.sleep(3000);
        thread.interrupt();
    }

    @Override
    public void run() {
        int count = 0;
        System.out.println("Thread.currentThread().isInterrupted()---> " + Thread.currentThread().isInterrupted());
        while (count <= 1000) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("执行中断.........");
                break;
            }

            if (count % 10 == 0) {
                System.out.println(count + "  是10的倍数");
            }
            count++;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("处理中断，并恢复中断..........");
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("任务运行结束...  当前 interrupt=" + Thread.currentThread().isInterrupted());

    }


}
